let instance = null
let uid = 0
const assets = {}
const noop = function () {
}
export default class Preload {
  constructor (native = false) {
    this._onProgress = noop
    this._onComplete = noop
    this.uid = ++uid
    this.assetId = `assets${this.uid}`
    this.loaded = 0
    this.loadTotal = 0
    this.native = native
    assets[this.assetId] = {}
  }

  /**
   * @description 生成一个单例
   * @return {null}
   */
  static get instance () {
    if (!instance) {
      instance = new Preload()
    }
    return instance
  }

  /**
   * @description 创建一个新的Preload
   * @return {Preload}
   */
  static create (native = false) {
    return new Preload(native)
  }

  // eslint-disable-next-line accessor-pairs
  set onProgress (callback) {
    if (typeof callback !== 'function') return
    this._onProgress = callback
  }

  // eslint-disable-next-line accessor-pairs
  set onComplete (callback) {
    if (typeof callback !== 'function') return
    this._onComplete = callback
  }

  /**
   * @description 返回获取生成完的资源
   * @return {*}
   */
  get assets () {
    return assets[this.assetId]
  }

  /**
   * @description 加载资源
   * @param assets
   */
  loadAssets (assets) {
    if (!assets || (Array.isArray(assets) && !assets.length)) {
      this._onComplete()
      return
    }
    this.loaded = 0
    this.loadTotal = assets.length
    for (let i = 0; i < this.loadTotal; i++) {
      const src = typeof assets[i] === 'string' ? assets[i] : assets[i].src
      const img = new Image()
      img.onload = img.onerror = () => {
        img.onload = img.onerror = null
        this.loaded++
        this._onProgress(this.loaded, this.loadTotal)
        if (this.loaded >= this.loadTotal) {
          this._onComplete()
        }
      }
      img.src = src
    }
  }
}
